import { toast } from 'sonner';

# Toast()

Use it to render a toast. You can call it from anywhere, even outside of React.

## Rendering the toast

You can call it with just a string.

```jsx
import { toast } from 'sonner';

toast('Hello World!');
```

Or provide an object as the second argument with more options. They will overwrite the options passed to [`<Toaster />`](/toaster) if you have provided any.

```jsx
import { toast } from 'sonner';

toast('My toast', {
  className: 'my-classname',
  description: 'My description',
  duration: 5000,
  icon: <MyIcon />,
});
```

### Render toast on page load

To render a toast on initial page load it is required that the function `toast()` is called inside of a `setTimeout` or `requestAnimationFrame`.

```jsx
setTimeout(() => {
  toast('My toast on a page load');
});
```

## Creating toasts

### Success

Renders a checkmark icon in front of the message.

```jsx
toast.success('My success toast');
```

### Error

Renders an error icon in front of the message.

```jsx
toast.error('My error toast');
```

### Action

Renders a primary button, clicking it will close the toast and run the callback passed via `onClick`. You can prevent the toast from closing by calling `event.preventDefault()` in the `onClick` callback.

```jsx
toast('My action toast', {
  action: {
    label: 'Action',
    onClick: () => console.log('Action!'),
  },
});
```

You can also render jsx as your action.

```jsx
toast('My action toast', {
  action: <Button onClick={() => console.log('Action!')}>Action</Button>,
});
```

### Cancel

Renders a secondary button, clicking it will close the toast and run the callback passed via `onClick`.

```jsx
toast('My cancel toast', {
  cancel: {
    label: 'Cancel',
    onClick: () => console.log('Cancel!'),
  },
});
```

You can also render jsx in the cancel option.

```jsx
toast('My cancel toast', {
  cancel: <Button onClick={() => console.log('Cancel!')}>Cancel</Button>,
});
```

### Promise

Starts in a loading state and will update automatically after the promise resolves or fails.
You can pass a function to the success/error messages to incorporate the result/error of the promise.

```jsx
toast.promise(myPromise, {
  loading: 'Loading...',
  success: (data) => {
    return `${data.name} toast has been added`;
  },
  error: 'Error',
});
```

### Loading

Renders a toast with a loading spinner. Useful when you want to handle various states yourself instead of using a promise toast.

```jsx
toast.loading('Loading data');
```

### Custom

You can pass jsx as the first argument instead of a string to render a custom toast while maintaining default styling.

```jsx
toast(<div>A custom toast with default styling</div>, { duration: 5000 });
```

### Headless

Use it to render an unstyled toast with custom jsx while maintaining the functionality. This function receives the `Toast` as an argument, giving you access to all properties.

```jsx
toast.custom((t) => (
  <div>
    This is a custom component <button onClick={() => toast.dismiss(t)}>close</button>
  </div>
));
```

### Dynamic Position

You can change the position of the toast dynamically by passing a `position` prop to the toast
function. It will not affect the positioning of other toasts.

```jsx
// Available positions:
// top-left, top-center, top-right, bottom-left, bottom-center, bottom-right
toast('Hello World', {
  position: 'top-center',
});
```

## Other

### Updating toasts

You can update a toast by using the `toast` function and passing it the id of the toast you want to update, the rest stays the same.

```jsx
const toastId = toast('Sonner');

toast.success('Toast has been updated', {
  id: toastId,
});
```

### On Close Callback

You can pass `onDismiss` and `onAutoClose` callbacks to each toast. `onDismiss` gets fired when either the close button gets clicked or the toast is swiped. `onAutoClose` fires when the toast disappears automatically after it's timeout (`duration` prop).

```jsx
toast('Event has been created', {
  onDismiss: (t) => console.log(`Toast with id ${t.id} has been dismissed`),
  onAutoClose: (t) => console.log(`Toast with id ${t.id} has been closed automatically`),
});
```

### Persisting toasts

If you want a toast to stay on screen forever, you can set the `duration` to [`Infinity`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity).

```js
toast('This toast will stay on screen forever', {
  duration: Infinity,
});
```

### Dismissing toasts programmatically

To remove a toast programmatically use `toast.dismiss(id)`. The `toast()` function return the id of the toast.

```jsx
const toastId = toast('Event has been created');

toast.dismiss(toastId);
```

You can also dismiss all toasts at once by calling `toast.dismiss()` without an id.

```jsx
toast.dismiss();
```

### Rendering custom elements

You can render custom elements inside the toast like `<a />` or custom components by passing a function instead of a string. This work for both the title and description.

```jsx
toast(
  () => (
    <>
      View{' '}
      <a href="https://google.com" target="_blank">
        Animation on the Web
      </a>
    </>
  ),
  {
    description: () => <button>This is a button element!</button>,
  },
);
```

### Targeting a specific Toaster

You can target a specific Toaster by passing a `toasterId` option:

```jsx
// This toast will only appear in the Toaster with id="canvas"
toast('This will show in the canvas Toaster', { toasterId: 'canvas' });
```

## API Reference

| Property          |                                              Description                                               |        Default |
| :---------------- | :----------------------------------------------------------------------------------------------------: | -------------: |
| description       |                           Toast's description, renders underneath the title.                           |            `-` |
| closeButton       |                                          Adds a close button.                                          |        `false` |
| invert            |                                Dark toast in light mode and vice versa.                                |        `false` |
| duration          |            Time in milliseconds that should elapse before automatically closing the toast.             |         `4000` |
| position          |                                         Position of the toast.                                         | `bottom-right` |
| dismissible       |                     If `false`, it'll prevent the user from dismissing the toast.                      |         `true` |
| icon              |                      Icon displayed in front of toast's text, aligned vertically.                      |            `-` |
| action            |                      Renders a primary button, clicking it will close the toast.                       |            `-` |
| cancel            |                     Renders a secondary button, clicking it will close the toast.                      |            `-` |
| id                |                                        Custom id for the toast.                                        |            `-` |
| onDismiss         |       The function gets called when either the close button is clicked, or the toast is swiped.        |            `-` |
| onAutoClose       | Function that gets called when the toast disappears automatically after it's timeout (duration` prop). |            `-` |
| unstyled          |                  Removes the default styling, which allows for easier customization.                   |        `false` |
| actionButtonStyle |                                      Styles for the action button                                      |           `{}` |
| cancelButtonStyle |                                      Styles for the cancel button                                      |           `{}` |
